package com.ruoyi.Apps.advice;
import com.ruoyi.Apps.Utils.I18nUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.I18nException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Locale;

@RestControllerAdvice
public class I18ExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(I18ExceptionHandler.class);
    /**
     * 处理 I18nException 异常
     */
    @ExceptionHandler(I18nException.class)
    @ResponseBody
    public AjaxResult handleI18nException(I18nException e) {
        log.warn("业务异常: {}", e.getMessageKey(), e);

        // 确定locale
        Locale locale = e.getLocale();
        if (locale == null) {
            locale = I18nUtil.getLocaleFromRequest();
        }

        // 获取国际化消息
        String message = I18nUtil.getMessage(e.getMessageKey(), e.getArgs(), locale);

        return AjaxResult.error(message);
    }

}
